package com.github.xzb617.config;

import com.github.xzb617.security.authc.AuthcInterceptor;
import com.github.xzb617.security.client.ClientInterceptor;
import com.github.xzb617.security.perms.PermsInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * WebMVC配置
 * <p>
 *     跨域、拦截器、静态资源映射
 * </p>
 * @author xzb617
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private AuthcInterceptor authcInterceptor;
    @Resource
    private ClientInterceptor clientInterceptor;
    @Resource
    private PermsInterceptor permsInterceptor;

    /**
     * 注册拦截器
     * <p>
     *     /pages/**: 该路径是将前端页面整合到项目中来，用来访问的页面，因此需要放行
     * </p>
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.authcInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/pages/**");
        registry.addInterceptor(this.clientInterceptor)
                .addPathPatterns("/**");
        registry.addInterceptor(this.permsInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/pages/**");
    }

    /**
     * CORS过滤器
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**")
                .addResourceLocations("classpath:static/");
    }
}
